package com.wstuo.common.config.onlinelog.action;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.wstuo.common.config.onlinelog.dto.UserOnlineLogDTO;
import com.wstuo.common.config.onlinelog.service.IUserOnlineLogService;
import com.wstuo.common.security.enums.SessionName;
import com.wstuo.common.security.service.IUserInfoService;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * UserOnlineLog SessionListener
 * 
 * @author spring date:2010-10-11
 */
public class UserOnlineLogSessionListener implements HttpSessionListener,
		HttpSessionAttributeListener {
	private static final Logger LOGGER = Logger.getLogger(UserOnlineLogSessionListener.class );    
	public void sessionCreated(HttpSessionEvent se) {

	}

	/**
	 * Destruction occurred
	 */
	@SuppressWarnings("unchecked")
	public void sessionDestroyed(final HttpSessionEvent se) {
		HttpSession session = se.getSession();
		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
		IUserOnlineLogService userservice = (IUserOnlineLogService) ctx.getBean("useronlinelogService");
		
		try {
			//会话过期时,非终端用户数量-1
			IUserInfoService userInfoService = (IUserInfoService) ctx.getBean("userInfoService");
			String loginName = (String) session.getAttribute("loginUserName");//获取当前超时用户的登录名
			if (loginName != null&&userInfoService.checkNonTerminal(loginName)) {//判断是否非终端用户
				ServletContext application = se.getSession()
						.getServletContext();
				if(application!=null&&application.getAttribute("nonTerminal")!=null
						&&!"admin".equalsIgnoreCase(loginName)){
					if(application.getAttribute("sessionMap")!=null){
						String loginNormal=loginName+"normal";
						String loginMobile=loginName+"mobile";
						Boolean result=false;//是否是相同的帐号
						Map<String, HttpSession> sessionMap = (HashMap<String, HttpSession>) application.getAttribute("sessionMap");
						if (sessionMap!=null && (((loginNormal !=null && sessionMap.containsKey(loginNormal))
								|| (loginNormal !=null && sessionMap.containsKey(loginNormal.toLowerCase())) 
								|| (loginNormal !=null && sessionMap.containsKey(loginNormal.toUpperCase())))
								|| ((loginMobile !=null && sessionMap.containsKey(loginMobile))
								|| (loginMobile !=null && sessionMap.containsKey(loginMobile.toLowerCase())) 
								|| (loginMobile !=null && sessionMap.containsKey(loginMobile.toUpperCase()))))) {
							result=true;
						}
						if(!result){
							application.setAttribute("nonTerminal",((Integer)application.getAttribute("nonTerminal")) - 1);// 非终端用户数量-1
						}
						LOGGER.debug("the num of technician subtract 1 , the technician 's name is "+loginName);
					}else{
						LOGGER.debug("sessionMap is null, the technician 's name is "+loginName);
					}
				}
			}
		} catch (BeansException e) {
			LOGGER.error("session Destroyed by exception", e);
		}

		if( null != session && null != SessionName.LOGINNAME.getName() && 
		        null != session.getAttribute(SessionName.LOGINNAME.getName())){
			userservice.offline(session.getId(),session.getAttribute(SessionName.LOGINNAME.getName()).toString() );
		}
		ServletContext sctx = ctx.getServletContext();// 取得ServletContext容器
		String userName = userservice.getUserName(session.getId());// 登录用户名

		if (sctx != null && sctx.getAttribute("sessionMap") != null) {// 将超时的用户从Map中移除

			Map<String, HttpSession> sessionMap = (HashMap<String, HttpSession>) sctx
					.getAttribute("sessionMap");

			if (sessionMap.get(userName) != null) {// 移除Map中的项，并更新Map
				sessionMap.remove(userName);
				sctx.setAttribute("sessionMap", sessionMap);
			}
		}

		if (session.getAttribute("userCompanyNo") != null) {// 异常session
			session.removeAttribute("userCompanyNo");
		}

	}

	/**
	 * Create a property occurs
	 */
	public void attributeAdded(HttpSessionBindingEvent se) {
		if ("loginUserName".equals(se.getName())) {

			HttpSession session = se.getSession();
			WebApplicationContext ctx = WebApplicationContextUtils
					.getWebApplicationContext(session.getServletContext());
			IUserOnlineLogService userservice = (IUserOnlineLogService) ctx
					.getBean("useronlinelogService");

			UserOnlineLogDTO useronlinelogDto = new UserOnlineLogDTO();
			useronlinelogDto.setUserName(se.getValue().toString());
			useronlinelogDto.setSessionId(session.getId());
			useronlinelogDto.setOnlineTime(new Date(session.getCreationTime()));

			Long companyNo = userservice.findCompanyNoByUserName(se.getValue()
					.toString());
			if (companyNo != null) {
				useronlinelogDto.setCompanyNo(companyNo);
				session.setAttribute("userCompanyNo", companyNo);
			}

			userservice.online(useronlinelogDto);

		}
	}

	/**
	 * AttributeRemoved
	 */
	public void attributeRemoved(HttpSessionBindingEvent arg0) {
	}

	/**
	 * AttributeReplaced
	 */
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
	}
}